package com.smart.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectTest {

    public static void main(String[] args) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        try {
            Class<?> clazz = classLoader.loadClass("com.smart.reflect.Car");
            Constructor<?> constructor = clazz.getDeclaredConstructor((Class<?>[]) null);
            constructor.setAccessible(true);
            Car car = (Car) constructor.newInstance();
            Method setBrand = clazz.getDeclaredMethod("setBrand", String.class);
            setBrand.setAccessible(true);
            setBrand.invoke(car, "奥迪");
            Method setColor = clazz.getDeclaredMethod("setColor", String.class);
            setColor.setAccessible(true);
            setColor.invoke(car, "红色");
            Method setMaxSpeed = clazz.getDeclaredMethod("setMaxSpeed", int.class);
            setMaxSpeed.setAccessible(true);
            setMaxSpeed.invoke(car, 300);
            System.out.println(car);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

}
